from dataclasses import dataclass
from enum import unique
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from sqlalchemy import true
from datetime import datetime
# 实例化一个flaskApp
app = Flask(__name__)

# 配置数据表
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:Aa112211@106.225.212.141:3306/test"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config['SECRET_KEY'] = 'qinghuan'
# 实例化数据库
db = SQLAlchemy(app)

# 建
# 管理员表
class Admin(db.Model):
    __tablename_ =  'admin'
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(100),nullable=False,unique=True)     #账号
    password = db.Column(db.String(100),nullable=False)     #密码
    tip = db.relationship('Tips',backref='admin')           #标签与管理员关联
# 用户表    unique约束 唯一性
class Users(db.Model):
    __tablename_ =  'users'
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(100),nullable=False,unique=True)     #账号
    password = db.Column(db.String(100),nullable=False)     #密码
    messages = db.relationship('Message',backref='users')   #留言与用户关联
# 留言条表
class Message(db.Model):
    __tablename_ =  'message'
    id = db.Column(db.Integer,primary_key=True)
    content = db.Column(db.String(256),nullable=False)     #内容
    creat_time = db.Column(db.DateTime,default=datetime.now)    #发布时间，datetime.now获取当前时间
    uesr_id = db.Column(db.String(256),db.ForeignKey('users.id'))   #与用户建立外键
    tipss = db.relationship('Tips',secondary='message_to_tips',backref='messages')  #关联关系 
# 标签
class Tips(db.Model):
    __tablename_ =  'tips'
    id = db.Column(db.Integer,primary_key=True)           #主键
    content = db.Column(db.String(10),nullable=False)     #内容
    admin_id = db.Column(db.Integer,db.ForeignKey('admin.id'))  #与admin建立外键

#处理留言条和标签，建立中间表
class MessageToTips(db.Model):
    __tablename__ = 'message_to_tips'
    id = db.Column(db.Integer,primary_key=True)           #主键
    message_id = db.Column(db.Integer,db.ForeignKey('message.id', ondelete='CASCADE'))   #与留言表建立外键
    tips_id = db.Column(db.Integer,db.ForeignKey('tips.id', ondelete='CASCADE'))         #与标签建立外键


if __name__ == '__main__':
    db.create_all()
    # db.drop_all()
